<template>
  <p-modal
      v-model="visible"
      :title="'选择物料'"
      :width="1300"
    >
      <div style="display:flex;align-items: center;">
        <div style="width:240px;">
          <p-input-search
            allow-clear
            v-model="keyword"
            :placeholder="'请输入物料编码或名称'"
          />
        </div>
        <p-button
          type="primary"
          style="margin-left:10px;"
          @click="loadData()"
        >
          搜索
        </p-button>
      </div>
      <p-table
        v-if="tableFlag"
        ref="tableRef"
        :data-source="tableData"
        :columns="curCols"
        :pagination="ipagination"
        row-key="mcode"
         @change="tableChange"
        style="width: 100%;margin-top:16px;"
        :row-selection="{ getCheckboxProps:getCheckboxProps,selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      >

      </p-table>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <div class="cText">
          <!-- <span>已选择({{ chooseList.length }})</span> -->
        </div>
        <div class="modal-footer-scroll">
          <p-tag
            v-for="item in chooseList"
            :key="item.mcode"
            closable
            size="mini"
            style="margin-right:10px;"
            @close="removeChoose(item.mcode)"
          >
            {{ item[tagName] || '' }}
          </p-tag>
        </div>
        <p-button
          type="primary"
          @click="confirmChoose"
        >
          确 定
        </p-button>
      </div>
      </p-dialog>
    </p-modal>
</template>

<script>
import { cloneObject } from '@u/util'
import { userList } from '@/api/manage'
import mesPeProcess from "@/api/mesPeProcess";
import { postAction, getAction, deleteAction } from "@/api/manage";
import mixins from './mixins'
import _ from "lodash";
export default {
  name: 'ChooseCon',
  mixins: [mixins],
  props: {
    x: {
      type: Number,
      default: () => {
        return 0;
      }
    },
    tagName: {
      type: String,
      default: () => {
        return 'name';
      }
    },
    title: String,
    columns: Array,
  },
  data () {
    return {
      searchDept: '',
      tableFlag: true,
      orgOptions: [],
      emptyText: '请选择',
      chooseList: [],
      selectedRowKeys: [],
      maintenanceKeyList: [
        {
          value: '1',
          label: '是',
        },
        {
          value: '2',
          label: '否',
        },
      ],
      visible: false,
      keyword: '',
      curCols: [],
      tableDataCopy: [],
     
      tableData: [],
      selectedRows:[],
      tableDataMock: [
        {
          allQuantity: 2,
          bomGroup: "A",
          bomLevel: 1,
          id: null,
          maintenanceKey: "0",
          maintenanceSap: "0",
          mcode: "O50120190148",
          mexplain: "qwert",
          mname: "名称TestBom02_01",
          remainQuantity: 2,
          sprc: "QWERT",
          stationId: null,
          stationsRequired: null,
          unit: null,
          workstationCode: null,
          workstationName: null,
        },
        {
          allQuantity: 2,
          bomGroup: "A",
          bomLevel: 1,
          id: null,
          maintenanceKey: "0",
          maintenanceSap: "0",
          mcode: "O50100030189",
          mexplain: "qwert",
          mname: "名称TestBom02_02",
          remainQuantity: 2,
          sprc: "QWERT",
          stationId: null,
          stationsRequired: null,
          unit: null,
          workstationCode: null,
          workstationName: null,
        }
      ],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ["10", "20", "50"],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条";
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      url:{
        list:'/basic-business/auto/baCpinfoMain/list'
      }
    }
  },
  computed: {
    form(){
      return this.$parent.$parent.$parent.$refs.BaseInfo.form;
    },
    // workstationCode(){
    //   return this.$parent.$parent.curSelectedNodes.processmcode;
    // },
    productCode(){
      return this.$parent.$parent.$parent.$refs.BaseInfo.form.productCode;
    },
    /* curPens(){
      return this.$parent.$parent.canvas.data.pens;
    }, */
  },
  watch:{
   
    selectedRowKeys(val){
      this.chooseList = this.tableDataCopy.filter(item => this.selectedRowKeys.includes(item.mcode));
    },
  },
  mounted () {
    this.curCols = this.getCols();
    this.loadData()
  },
  methods: {
    loadData(){
      let obj={
        pageNo:this.ipagination.current,
        limit:this.ipagination.pageSize,
        type:3,
        keyword:this.keyword
      }
      getAction(this.url.list,obj).then(res=>{
        if(res.code==0){
          this.tableData=res.data.records
          this.ipagination.total=res.data.total
        }
      })
    },
    formatter(value){
      let str = value;
      if (value){
        str =  `${value}`.replace(/\D*/g, '');
      }else {
        str = 0;
      }
      return str;
    },
    parserValue(value){
      let str = value;
      if (value){
        str =  `${value}`.replace(/\D*/g, '');
      }else {
        str = 0;
      }
      return str;
    },
    copyTableData(){
      this.tableDataCopy = _.cloneDeep(this.tableData);
    },
    replaceSomeTableData(){
      this.tableDataCopy.forEach( (ele, index) =>{
        this.tableData.forEach( el =>{
          if ( ele.mcode === el.mcode ){
            this.tableDataCopy[index] = _.cloneDeep(el);
          }
        });
      });
    },
    getCheckboxProps: record => ({
      props: {
        disabled: record.stationsRequired === 0, // Column configuration not to be checked
      },
    }),
    
    
    stationsRequiredChange(row){
      const stationsRequiredOrigin = row.stationsRequiredOrigin;
      row.remainQuantity = ( row.allQuantity - (row.allStationsRequired - stationsRequiredOrigin) ) - row.stationsRequired;
      // 数量大于1 自动选中 等于0 自动取消选中
      if(row.stationsRequired > 0){
        if(!this.selectedRowKeys.includes(row.mcode)){
          this.selectedRowKeys.push(row.mcode);
        }
      }else {
        if(this.selectedRowKeys.includes(row.mcode)){
          this.selectedRowKeys = this.selectedRowKeys.filter( el => el !== row.mcode );
        } 
      }
      this.replaceSomeTableData();
      this.tableData.splice();
      console.log(row.stationsRequired);
    },
    getCols(){
      let cols = _.cloneDeep(this.columns);
      cols = cols.slice(0, cols.length - 3);
      const index1 = cols.findIndex( el => el.dataIndex === 'stationsRequired' );
      return cols;
    },
    onSelectChange(selectedRowKeys, selectedRows){
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows=selectedRows
    },
    tableChange (pageOptions) {
      this.ipagination=pageOptions
      this.loadData()
    },
    confirmChoose(){
      this.visible=false
      this.selectedRows.map(item=>{item.change=true})
      
      this.$emit('confirm',this.selectedRows)
    },
    handleCancel(){
      this.visible=false
    },
    removeChoose (mcode) {
      this.selectedRowKeys = this.selectedRowKeys.filter( el => el !== mcode);
    },
  }
}
</script>

<style scoped lang="less">
.choose-items-con {
  border: solid 1px #DEDEDF;
  border-radius: 4px;
  box-sizing: border-box;
  color: #606266;
  transition: border-color .2s;
  display: flex;
  width: 100%;
  cursor: pointer;
  &:hover {
      border-color: #C0C4CC;
  }
  .tags{
      width:calc(100% - 25px);
      max-height: 160px;
      overflow-y: auto;
      padding-left: 15px;
  }
  .empty{
    opacity:0.6;
  }
  .icon{
      width:25px;
      cursor: pointer;
      transition: transform .3s;
      text-align: center;
      &.active{
          transform: rotate(180deg);
      }
  }
}

.dialog-footer{
  display:flex;
  align-items:center;
  .cText{
    word-break: keep-all;
    white-space: nowrap;
  }
}

.modal-footer-scroll {
    width: 100%;
    text-align: left;
    overflow-x: auto;
    overflow-y: hidden;
    white-space: nowrap;
    margin:0 16px;
    padding: 6px 0;
}
.select-down .a-select-dropdown__item{
  padding:0;
}
.errorClass{
  border-color: rgba(245, 117, 117, 0.9);
}

</style>
<style lang="less">
.overlayClassName{
  .poros-tooltip-inner{
    background-color: rgba(245, 117, 117, 0.9);
  }
  .poros-tooltip-arrow::before{
    background-color: rgba(245, 117, 117, 0.9);
  }
}
</style>
